﻿<!DOCTYPE HTML>
<html lang="zh">
<head>
<title>If - 语法 &amp; 使用 | AutoHotkey v2</title>
<meta name="description" content="The If statement specifies one or more statements to execute if an expression evaluates to true." />
<meta name="ahk:equiv-v1" content="commands/IfExpression.htm" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
<script type="text/javascript">$(function(){0<=window.navigator.userAgent.toLowerCase().indexOf("ucbrowser")&&CaoNiMaDeUc()})</script>
</head>
<body>

<h1>if (表达式)</h1>

<p>指定在<a href="../Variables.htm#Expressions">表达式</a>计算结果为 True(真) 时要执行的<a href="../Concepts.htm#statement">语句</a>.</p>
<pre class="Syntax"><span class="func">If</span> (<i>表达式</i>)
{
    <i>语句</i>
}</pre>

<h2 id="Remarks">备注</h2>
<p>如果 <em>If</em> 语句的表达式的计算结果为 true(即除空字符串或数字 0 以外的任何结果), 则执行其下面的行或<a href="Block.htm">区块</a>. 否则, 如果存在相应的 <a href="Else.htm">Else</a> 语句, 则执行将跳转到其下面的行或区块.</p>
<p>如果指定要执行多个语句, 则这些语句必须用大括号括起来(以创建<a href="Block.htm">区块</a>). 否则, 大括号是可选的. 请参阅本页底部的示例.</p>
<p>如果表达式以小括号开头, 则 <code>if</code>后面的空格是可选的, 例如 <code>if(expression)</code>.</p>
<p id="otb">可以选择使用 One True Brace(OTB) 样式. 例如:</p>
<pre>if (x &lt; y) {
    <em>; ...</em>
}
if WinExist(&quot;Untitled - Notepad&quot;) {
    WinActivate
}
if IsDone {
    <em>; ...</em>
} else {
    <em>; ...</em>
}</pre>
<p>与 <em>If</em> 语句不同, <a href="Else.htm">Else</a> 语句支持任何类型的语句紧跟在其右边.</p>

<h2 id="Related">相关</h2>
<p><a href="../Variables.htm#Expressions">Expressions</a>, <a href="SetExpression.htm">Assign expression (:=)</a>, <a href="../Variables.htm#ternary">Ternary operator (a?b:c)</a>, <a href="Block.htm">Blocks</a>, <a href="Else.htm">Else</a>, <a href="While.htm">While-loop</a></p>

<h2 id="Examples">示例</h2>
<div class="ex" id="ExBasic">
<p><a href="#ExBasic">#1</a></p>
<pre>if (A_Index &gt; 100)
    return

if (A_TickCount - StartTime &gt; 2*MaxTime + 100)
{
    MsgBox "Too much time has passed."
    ExitApp
}

if (Color = &quot;Blue&quot; or Color = &quot;White&quot;)
{
    MsgBox "The color is one of the allowed values."
    ExitApp
}
else if (Color = &quot;Silver&quot;)
{
    MsgBox "Silver is not an allowed color."
    return
}
else
{
    MsgBox "This color is not recognized."
    ExitApp
}</pre>
</div>

</body>
</html>